package jcu.ict.profaid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteCursor;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class FormListQuestion extends Activity {
	private static QuestionDbAdapter qdb;
	private String id_course;
	private String QuestionId;
	private ListView lv_course;
	private MyAdapter favContexted;
	private AdapterContextMenuInfo menuInfo;
	private SessionManager session;
	private String Loginemail;
	private AnswerDbAdapter adb;
	private EditText inputSearch;
	private String user_id;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		session = new SessionManager(getApplicationContext());
		session.checkLogin();
		
		Bundle bundle = this.getIntent().getExtras();
		String i = (String) bundle.getCharSequence("setInfoCourse");
		user_id = (String) bundle.getCharSequence("setUserId");
		
		id_course = i;

		setContentView(R.layout.form_my_question);

		lv_course = (ListView) findViewById(R.id.lstMyQuestion);

		qdb = new QuestionDbAdapter(getBaseContext());

		qdb.open();

		ArrayList<Object> listCourse = PopulateList(null);
		favContexted = new MyAdapter(this, R.layout.listview_display,
				R.id.txtUp, listCourse);
		lv_course.setAdapter(favContexted);

		registerForContextMenu(lv_course);
		
		inputSearch = (EditText) findViewById(R.id.edtSearch);
		
		inputSearch.addTextChangedListener(new TextWatcher() {
		     
		    @Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        // When user changed the Text
		    	 FormListQuestion.this.favContexted.getFilter().filter(cs);
		    }
		     
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) {
		        // TODO Auto-generated method stub
		         
		    }
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		lv_course.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String i = arg0.getItemAtPosition(arg2).toString();

				String[] info = i.split(",");
				String[] updateId = info[4].split("]");

				QuestionId = updateId[0];

				qdb.close();

				Intent in = new Intent(FormListQuestion.this, MainResult.class);
				Bundle bundle = new Bundle();
				bundle.putString("setQuestionId", QuestionId);
				bundle.putString("setInfoCourse", id_course);
				bundle.putCharSequence("setUserId", user_id);
				in.putExtras(bundle);
				startActivity(in);
				finish();
			}
		});
	}
	
	private ArrayList<Object> PopulateList(String abc) {
		// TODO Auto-generated method stub
		SQLiteCursor krsr = null;
		try {
			krsr = (SQLiteCursor) qdb.populateQuestion(user_id,id_course);

		} catch (Exception ex) {
			Log.e("salah", ex.toString());
			return null;
		}

		ArrayList<Object> queryResult = new ArrayList<Object>();
		final int colCnt = krsr.getColumnCount();

		while (krsr.moveToNext()) {
			ArrayList<Object> satuRow = new ArrayList<Object>();
			for (int i = 0; i < colCnt; i++) {
				/**
				 * In android 2.2 isNull is not exclusive so we need elseif's
				 */
				if (krsr.isNull(i)) {
					satuRow.add("");
				} else if (krsr.isString(i)) {
					satuRow.add(krsr.getString(i));
				} else if (krsr.isLong(i)) { // integer
					satuRow.add(krsr.getLong(i));
				} else if (krsr.isFloat(i)) { // real
					satuRow.add(krsr.getDouble(i));
				} else if (krsr.isBlob(i)) {
					satuRow.add(krsr.getBlob(i));
				}
			}
			queryResult.add(satuRow);
		}

		krsr.close();
		return queryResult;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.add("Edit");
		menu.add("Delete");
		menu.add("Report");
		menu.add("Report and Reset Question");
	}

	@SuppressWarnings("null")
	public boolean onContextItemSelected(MenuItem item) {
		menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		if (item.getTitle() == "Edit") {
			ListAdapter adapter = lv_course.getAdapter();
			Object obj = adapter.getItem(menuInfo.position);
			String x = obj.toString();

			String[] info = x.split(",");
			String[] updateId = info[4].split("]");

			QuestionId = updateId[0];

			Intent in = new Intent(FormListQuestion.this,
					FormEditQuestion.class);
			Bundle bundle = new Bundle();
			bundle.putString("setQuestionId", QuestionId);
			bundle.putString("setInfoCourse", id_course);
			bundle.putCharSequence("setUserId", user_id);
			in.putExtras(bundle);
			startActivity(in);
			finish();
		} else if (item.getTitle() == "Delete") {
			ListAdapter adapter = lv_course.getAdapter();
			Object obj = adapter.getItem(menuInfo.position);
			String x = obj.toString();

			String[] info = x.split(",");
			String[] updateId = info[4].split("]");

			QuestionId = updateId[0];

			AlertDialog.Builder builder = new AlertDialog.Builder(
					FormListQuestion.this);
			builder.setMessage("Are you sure want to Delete this question?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									QuestionDbAdapter qdb = new QuestionDbAdapter(
											getBaseContext());
									qdb.open();

									if (qdb.DeleteQuestion(QuestionId,
											id_course) > 0) {
										Toast.makeText(getBaseContext(),
												"Delete Success!!",
												Toast.LENGTH_LONG).show();
									} else {
										Toast.makeText(
												getBaseContext(),
												"Delete Failed, Please Try Again!",
												Toast.LENGTH_LONG).show();
									}

									ListAdapter adapter = lv_course
											.getAdapter();
									Object obj = adapter
											.getItem(menuInfo.position);

									/* Remove it from the list. */
									favContexted.remove(obj);

									qdb.close();
								}
							})

					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();
			
		} else if (item.getTitle() == "Report") {

			adb = new AnswerDbAdapter(getBaseContext());

			ListAdapter adapter = lv_course.getAdapter();
			Object obj = adapter.getItem(menuInfo.position);
			String x = obj.toString();

			String[] info = x.split(",");
			String[] updateId = info[4].split("]");

			QuestionId = updateId[0];

			qdb.open();
			adb.open();

			android.database.Cursor xCursor = qdb.populateQuestionEdit(
					QuestionId, id_course);
			xCursor.moveToFirst();
			String subject = xCursor.getString(0);
			String bodyQuestion = xCursor.getString(1);

			android.database.Cursor aCursor = adb.TableAnswer(QuestionId);
			aCursor.moveToFirst();

			String body = null;

			String[] answer = new String[aCursor.getCount()];
			String[] sumAnswer = new String[aCursor.getCount()];
			String[] idAnswer = new String[aCursor.getCount()];

			for (int i = 0; i < aCursor.getCount(); i++) {
				idAnswer[i] = aCursor.getString(0);
				answer[i] = aCursor.getString(1);
				sumAnswer[i] = aCursor.getString(2);
				aCursor.moveToNext();
			}

			int sumAll = 0;

			/*Dont forget give credit*/
			
			/* populate answer 1 - 5 to put it in email */
			if (aCursor.getCount() == 2) {
				sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]);
				
				body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
						+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
						  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll ;

			} else if (aCursor.getCount() == 3) {
				sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]);
				body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
						+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
						  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
						  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll ;

			} else if (aCursor.getCount() == 4) {
				sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]) + Integer.parseInt(sumAnswer[3]);
				body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
						+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
						  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
						  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll + "\nD." + 
						  answer[3] + ". Total: " + sumAnswer[3] + " out of " + sumAll ;

			} else if (aCursor.getCount() == 5) {
				sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]) + Integer.parseInt(sumAnswer[3]) + Integer.parseInt(sumAnswer[4]);
				body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
						+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
						  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
						  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll + "\nD." + 
						  answer[3] + ". Total: " + sumAnswer[3] + " out of " + sumAll + "\nE." +
						  answer[4] + ". Total: " + sumAnswer[4] + " out of " + sumAll ;
			}

			Intent email = new Intent(Intent.ACTION_SEND);
			email.putExtra(Intent.EXTRA_EMAIL, new String[] { Loginemail });
			email.putExtra(Intent.EXTRA_SUBJECT, subject);
			email.putExtra(Intent.EXTRA_TEXT, body);

			// need this to prompts email client only
			email.setType("message/rfc822");

			startActivity(Intent.createChooser(email,
					"Choose an Email client :"));

			// reset all
			for (int i = 0; i < aCursor.getCount(); i++) {
				adb.ResetAnswer(idAnswer[i]);
			}

			qdb.close();
			adb.close();
								
						
			
		} else if (item.getTitle() == "Report and Reset Question") {

			adb = new AnswerDbAdapter(getBaseContext());

			ListAdapter adapter = lv_course.getAdapter();
			Object obj = adapter.getItem(menuInfo.position);
			String x = obj.toString();

			String[] info = x.split(",");
			String[] updateId = info[4].split("]");

			QuestionId = updateId[0];

			AlertDialog.Builder builder = new AlertDialog.Builder(
					FormListQuestion.this);
			builder.setMessage("Are you sure want to Reset and Report this question?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									qdb.open();
									adb.open();

									android.database.Cursor xCursor = qdb.populateQuestionEdit(
											QuestionId, id_course);
									xCursor.moveToFirst();
									String subject = xCursor.getString(0);
									String bodyQuestion = xCursor.getString(1);

									android.database.Cursor aCursor = adb.TableAnswer(QuestionId);
									aCursor.moveToFirst();

									String body = null;

									String[] answer = new String[aCursor.getCount()];
									String[] sumAnswer = new String[aCursor.getCount()];
									String[] idAnswer = new String[aCursor.getCount()];

									for (int i = 0; i < aCursor.getCount(); i++) {
										idAnswer[i] = aCursor.getString(0);
										answer[i] = aCursor.getString(1);
										sumAnswer[i] = aCursor.getString(2);
										aCursor.moveToNext();
									}
									
									int sumAll = 0;

									/*Dont forget give credit*/
									
									/* populate answer 1 - 5 to put it in email */
									if (aCursor.getCount() == 2) {
										sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]);
										
										body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
												+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
												  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll ;

									} else if (aCursor.getCount() == 3) {
										sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]);
										body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
												+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
												  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
												  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll ;

									} else if (aCursor.getCount() == 4) {
										sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]) + Integer.parseInt(sumAnswer[3]);
										body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
												+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
												  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
												  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll + "\nD." + 
												  answer[3] + ". Total: " + sumAnswer[3] + " out of " + sumAll ;

									} else if (aCursor.getCount() == 5) {
										sumAll = Integer.parseInt(sumAnswer[0]) + Integer.parseInt(sumAnswer[1]) + Integer.parseInt(sumAnswer[2]) + Integer.parseInt(sumAnswer[3]) + Integer.parseInt(sumAnswer[4]);
										body = "Question \n" + bodyQuestion + "\nAnswers : \nA."
												+ answer[0] + ". Total: " + sumAnswer[0] + " out of " + sumAll + "\nB." + 
												  answer[1] + ". Total: " + sumAnswer[1] + " out of " + sumAll + "\nC." + 
												  answer[2] + ". Total: " + sumAnswer[2] + " out of " + sumAll + "\nD." + 
												  answer[3] + ". Total: " + sumAnswer[3] + " out of " + sumAll + "\nE." +
												  answer[4] + ". Total: " + sumAnswer[4] + " out of " + sumAll ;
									}

									Intent email = new Intent(Intent.ACTION_SEND);
									email.putExtra(Intent.EXTRA_EMAIL, new String[] { Loginemail });
									email.putExtra(Intent.EXTRA_SUBJECT, subject);
									email.putExtra(Intent.EXTRA_TEXT, body);

									// need this to prompts email client only
									email.setType("message/rfc822");

									startActivity(Intent.createChooser(email,
											"Choose an Email client :"));

									// reset all
									try{
									for(int i = 0; i < aCursor.getCount(); i++){
										adb.ResetAnswer(idAnswer[i]);
									}
									}catch(Exception x){
										Toast.makeText(getBaseContext(), "Reset Answer Failed, Please Try Again!", Toast.LENGTH_LONG).show();
									}
									
									qdb.close();
									adb.close();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();
						
			
		}
		return true;
	}  
	
}